
import React, { Component } from 'react';
import { Space, Table, Popconfirm, Button, Input, Divider, Form, Drawer, message } from 'antd';
import axios from 'axios';
import { number } from 'prop-types';
const dataSource = [
  {
    key: '1',
    name: '胡彦斌1',
    age: 32,
    address: '西湖区湖底公园1号',
  },
  {
    key: '2',
    name: '胡彦祖',
    age: 42,
    address: '西湖区湖底公园1号',
  },
];
class Admin extends Component {
    formRef = React.createRef() //清空输入框内容
    formRef1 = React.createRef()
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            open1: false,
            rowid: null,
            key: 2,
            
           dataSource:[{
    key: '1',
    name: '胡彦斌1',
    number: 32,
   describe: '西湖区湖底公园1号',
  },
  {
    key: '2',
    name: '胡彦祖',
    number: 42,
   describe: '西湖区湖底公园1号',
  },],
     minValue: 0,
      maxValue: 3,

            columns: [
                { title: '角色名称', dataIndex: 'name', key: 'name', },
                { title: '角色描述', dataIndex: 'describe', key: 'describe', },
                { title: '员工数', dataIndex: 'number', key: 'number', },
                
                {
                    title: '操作',
                    key: 'action',
                    render: (_, record) => (
                        <Space size="middle">
                            <a className="action-link" onClick={this.showDrawer1.bind(this, record)}>查看</a>
                            <Popconfirm title="确定要删除吗?" onConfirm={this.deleteData.bind(this, record.id)} onCancel={this.onClose.bind(this)} okText="确定" cancelText="取消" >
                                <a className="action-link" style={{ color: record.obsoleted ? '#1890ff' : '#fa8c16' }} >删除</a>
                            </Popconfirm>
                        </Space>
                    ),
                },
            ],
            data: [], //储存axios获取到的数据
        }
    }
      handleChange = value => {
    if (value <= 1) {
      this.setState({
        minValue: 0,
        maxValue: 1
      });
    } else {
      this.setState({
        minValue: (value-1) * 3,
        maxValue: (value-1) * 3+ 3
      });
    }
  };


    //关闭新增信息对话框
    onClose = () => {
        this.setState({
            open: false
        });
      
    };
    //关闭修改信息对话框
    onClose1 = () => {
        this.setState({
            open1: false
        });
        message.error('取消操作');
    };
    //显示新增信息抽屉
    showDrawer = () => {
        this.setState({
            open: true
        });
    };
    //显示修改信息抽屉
    showDrawer1 = (r) => {
        this.setState({
            open1: true,
            rowid: r.id,         
        })
        setTimeout(() => {this.formRef1.current.setFieldsValue(r) }, 0);}; //设置 0 毫秒延迟回显数据
        
    //将数据显示在初始页面
    componentDidMount() {
        this.readData()
    }
    
    //实现读取数据——————get
    readData() {
            this.setState({
data:dataSource.slice(this.setState.minValue,this.maxValue)
              })
    }
    
    //新增信息时的Input输入框事件
    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
        console.log(e, 1111111);
        console.log(this.state.name);
    }
    //修改信息时的Input输入框事件
    handleChange1 = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }
    
    //新增数据——————post
    //新增、修改数据时提交失败时的提示信息
    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
        message.error("按照格式要求输入")
    };
    
    postData = () => {
        let addData = {
            key: this.state.key,
            name: this.state.name,
            describe: this.state.describe,
            number:this.state.number
        }
        this.setState({
            dataSource: [...this.state.dataSource, addData],
            key:this.state.key+1
        })
        this.formRef.current.resetFields() //新增成功后清空输入框中的数据，避免下次点击新增时出现上次输入的数据
    }
    
    // // 实现删除————————delete
    deleteData = (id) => {
        axios.delete(`http://....你的url/${id}`) //id前面的 / 不能省略
            .then(res => {
                message.success('删除成功');
                // console.log('删除成功')
                this.readData()
            })
    };
    
    //实现按照姓名查询数据
    queryfn = (e) => {
        let keyword = e.target.value
        clearTimeout(window.timer)  //防抖查询
        window.timer = setTimeout(() => {
            let data = this.state.data.filter(r => r.name === keyword)
            if (data.length !== 0) {
                this.setState({
                    data
                })
            }
        }, 500)
    }
    
    //实现修改数据——put或patch
    updateData = () => {
        axios.patch(`http://....你的url/${this.state.rowid}`, {
            name: this.state.name,
            age: this.state.age,
            sex: this.state.sex,
            address: this.state.address,
            phone: this.state.phone
        }).then(res => {
            message.success('修改成功');
            // console.log('修改成功')
            this.readData()
            this.setState({
                open1: false
            });
        }).catch(error => {
            message.error("按照格式要求输入")
        })
        this.formRef1.current.resetFields() //修改成功后清空输入框中的数据
    }
    
    render() {
        let data = this.state.data;
        let columns = this.state.columns;
        let { name, number,describe } = this.state;
        return (
            <div className="App">
                <Button type="primary" onClick={this.showDrawer.bind(this)} >添加信息 </Button>
                <Input placeholder="请根据姓名查找信息" style={{ marginLeft: '10px', width: '20%' }} onInput={this.queryfn} />
                
                <Table columns={columns} dataSource={this.state.dataSource} pagination={{
                    position: ['bottomRight'], defaultCurrent: [1], pageSizeOptions: [1, 2, 3, 4],defaultPageSize:[1],
                    showSizeChanger:true,  showQuickJumper:[true],showTotal:()=>`共${this.state.dataSource.length}条`
                }} >   </Table>

                <Drawer title="添加角色信息" onClose={this.onClose} open={this.state.open}>
                    <Form ref={this.formRef} onFinish={this.postData} onFinishFailed={this.onFinishFailed} autoComplete="off" >
                        <Form.Item
                            name="name"
                            label="角色名称"
                            rules={[{ required: true, message: '请输入角色名称', }, ] } >
                            <Input placeholder="请输入您的姓名" id="name" value={name} onChange={this.handleChange} title='输入2-6位中文汉字'/>
                        </Form.Item>
                        <Form.Item
                            name="describe"
                            label="角色描述"
                            rules={[{ required: true, message: '角色描述', },]}  >
                            <Input placeholder="请输入您的性别" id="describe" value={describe} onChange={this.handleChange} title='输入男或女' />
                        </Form.Item>
                        <Form.Item
                            name="number"
                            label="员工数"
                            rules={[{ required: true, message: '请输入员工数量', },]} >
                            <Input placeholder="请输入您的年龄" id="number" value={number} onChange={this.handleChange}  title='输入1-120之间的数字'/>
                        </Form.Item>
                        
                        <Button onClick={this.onClose.bind(this)}>取消</Button>
                        <Button  onClick={this.onClose} htmlType="submit" type="primary">完成 </Button>
                    </Form>
                </Drawer>

                {/* <Drawer title="修改个人信息" onClose={this.onClose1} open={this.state.open1}>
                    <Form ref={this.formRef1} onFinish={this.updateData} onFinishFailed={this.onFinishFailed} autoComplete="off" >
                        <Form.Item
                            name="name"
                            label="姓名"
                            rules={[{ required: true, message: '请输入您的姓名', },]}     >
                            <Input placeholder="请输入您的姓名" id="name" value={name} onChange={this.handleChange1} pattern="[\u4e00-\u9fa5]{2,6}$" title='输入2-6位中文汉字'/>
                        </Form.Item>
                        <Form.Item
                            name="sex"
                            label="性别"
                            rules={[{ required: true, message: '请输入您的性别', },]}  >
                            <Input placeholder="请输入您的性别" id="sex" value={sex} onChange={this.handleChange1} pattern="^[男|女]{1}$" title='输入男或女'/>
                        </Form.Item>
                        <Form.Item
                            name="age"
                            label="年龄"
                            rules={[{ required: true, message: '请输入您的年龄', },]} >
                            <Input placeholder="请输入您的年龄" id="age" value={age} onChange={this.handleChange1} pattern="^(?:[1-9][0-9]?|1[01][0-9]|120)$" title='输入1-120之间的数字'/>
                        </Form.Item>
                        <Form.Item
                            name="address"
                            label="家庭住址"
                            rules={[{ required: true, message: '请输入您的家庭住址', },]}   >
                            <Input placeholder="请输入您的家庭住址" id="address"  onChange={this.handleChange1} pattern="[\u4e00-\u9fa5]{1,100}$" title='输入有效中文汉字'/>
                        </Form.Item>
                        <Form.Item
                            name="phone"
                            label="联系电话"
                            rules={[{ required: true, message: '请输入您的联系电话', },]} >
                            <Input placeholder="请输入11位联系电话" id="phone" value={phone} onChange={this.handleChange1}  pattern="^1[0-9]{10}$" title='输入1开头的11位有效手机号'/>
                        </Form.Item>
                        <Button onClick={this.onClose1.bind(this)}>取消</Button>
                        <Button  htmlType="submit" type="primary">完成 </Button>
                    </Form>
                </Drawer> */}
            </div>
        );
    }
}
export default Admin;

